package cn.itcast.web.controller.cargo;

import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.utils.DownloadUtil;
import cn.itcast.vo.ContractProductVo;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cargo/contract/")
public class ExcelController extends BaseController {

    @Reference
    private ContractProductService contractProductService;

    /**
     * 进入下载的页面
     */
    @RequestMapping("/print")
    public String print() {
        return "cargo/print/contract-print";
    }


    /**
     * 基于EasyExcel完成出货表打印
     *  1、查询数据
     *  2、设置EasyExcel的文件下载信息
     *  3、调用EasyExcel的write方法，完成文件下载
     */
    @RequestMapping("/printEasyExcel")
    public void printEasyExcel(String inputDate) throws IOException {
        //1、查询数据
        List<ContractProductVo> list = contractProductService.findByShipTime(inputDate+"%");
        //2、设置EasyExcel的文件下载信息
        response.setContentType("application/vnd.ms-excel"); //下载excel
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("出货表", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        //3、调用EasyExcel的write方法，完成文件下载
        EasyExcel.write(response.getOutputStream()) //response的输出输出流
                 .head(ContractProductVo.class) //设置表头的对象字节码
                 .sheet("heima23") //设置页名称
                 .doWrite(list); //写入数据
    }


    /**
     * 模板打印
     *   请求连接：/printTemplate
     */
    @RequestMapping("/printTemplate")
    public void printTemplate(String inputDate) throws IOException {
        //1、构造数据
        List<ContractProductVo> list = contractProductService.findByShipTime(inputDate+"%");
        Map map = new HashMap();
        map.put("title1", "客户");
        String time = inputDate.replaceAll("-0", "-").replaceAll("-", "年");
        map.put("time", time);
        //2、加载数据模板
        String path = session.getServletContext().getRealPath("/")+"/make/tOUTPRODUCT.xlsx";
        //3、设置EasyExcel的文件下载头信息
        response.setContentType("application/vnd.ms-excel"); //下载excel
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("出货表", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        //4、调用工具类创建Excel对象
        ExcelWriter build = EasyExcel.write(response.getOutputStream()) //response的输出输出流
                .head(ContractProductVo.class) //设置表头的对象字节码
                .withTemplate(path)
                .build();
        //5、获取页对象
        WriteSheet sheet = EasyExcel.writerSheet().build();
        //6、填充map数据
        build.fill(map, sheet);
        //7、填充list数据
        build.fill(list, sheet);
        //8.属性资源，完成下载
        build.finish(); //下载excel文件，释放内存资源
    }


    /**
     * 出货表打印
     *  参数：inputDate（勾选的船期）  2019-08   -- 2019-8 -- 2019年9
     *  请求连接：printExcel
     * 业务逻辑：
            *  a：调用service查询数据库
     *  b：通过POI构造excel文件
     *  c：完成文件下载
     */
    @RequestMapping("/printExcel")
    public void printExcel(String inputDate) throws IOException {
        //a：调用service查询数据库
        List<ContractProductVo> list = contractProductService.findByShipTime(inputDate+"%");
        //b：通过POI构造excel文件
        //Workbook wb = new XSSFWorkbook();
        Workbook wb = new SXSSFWorkbook(); //支持百万数据Excel文件下载

        //创建页
        Sheet sheet = wb.createSheet();
        //创建大标题
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(1);
        cell.setCellValue(inputDate.replaceAll("-0", "-").replaceAll("-", "年")+"月份出货表");
        cell.setCellStyle(bigTitle(wb));
        //创建小标题
        row = sheet.createRow(1);
        String [] titles = new String[]{"","客户","订单号","货号","数量","工厂","工厂交期","船期","贸易条款" };

        for (int i = 0; i < titles.length; i++) {
            String title = titles[i];
            //4.2 创建每一个单元格
            cell = row.createCell(i);
            //4.3 设置单元格的内容
            cell.setCellValue(title);
            cell.setCellStyle(title(wb));
        }

        //5.循环数据列表，构造数据行内容
        int index = 2;
        for (ContractProductVo cp : list) {
                row = sheet.createRow(index);

                cell = row.createCell(1);
                cell.setCellValue(cp.getCustomName());
                //cell.setCellStyle(text(wb));

                cell = row.createCell(2);
                cell.setCellValue(cp.getContractNo());
               // cell.setCellStyle(text(wb));

                cell = row.createCell(3);
                cell.setCellValue(cp.getProductNo());
                //cell.setCellStyle(text(wb));

                cell = row.createCell(4);
                cell.setCellValue(cp.getCnumber());
               // cell.setCellStyle(text(wb));

                cell = row.createCell(5);
                cell.setCellValue(cp.getFactoryName());
               // cell.setCellStyle(text(wb));

                cell = row.createCell(6);
                cell.setCellValue(cp.getDeliveryPeriod());
               // cell.setCellStyle(text(wb));

                cell = row.createCell(7);
                cell.setCellValue(cp.getShipTime());
               // cell.setCellStyle(text(wb));

                cell = row.createCell(8);
                cell.setCellValue(cp.getTradeTerms());
               // cell.setCellStyle(text(wb));

                index++;

        }
        //c：完成文件下载
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        wb.write(bos);
        new DownloadUtil().download(bos,response,"出货表.xlsx");
    }

    //大标题的样式
    public CellStyle bigTitle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short)12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short)10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);				//横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线

        return style;
    }
}
